package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Question;
import cn.wolfcode.domain.QuestionItem;
import cn.wolfcode.service.IQuestionService;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/question")
public class QuestionController {

    @Autowired
    private IQuestionService questionService;


    @RequiredPermission(name="题目页面",expression="question:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Question> pageInfo = questionService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "question/list";
    }


    @RequiredPermission(name="题目删除",expression="question:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
           questionService.delete(id);
        }
        return "redirect:/question/list";
    }


    @RequiredPermission(name="题目新增/编辑",expression="question:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Question question) {
        if (question.getId() == null) {
            questionService.save(question);
        } else {
            questionService.update(question);
        }
        return "redirect:/question/list";
    }


    @RequiredPermission(name="题目新增/编辑",expression="question:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("question",questionService.get(id));
        }
        return "question/input";
    }


    @RequestMapping("/findItems")
    @ResponseBody
    public List<QuestionItem> findItems(Long questionId){
        List<QuestionItem> questionItems = questionService.selectItemsByQuestionId(questionId);
        return questionItems;
    }
}
